package com.cn.shuangzi.userinfo.common;


import android.text.TextUtils;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.userinfo.R;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by CN on 2016/11/14.
 */

public class OSSManager {
    private String endpoint;
    private String bucket;
    private OSSClient oss;
    //    private static OSSManager INSTANCE;
    private static SimpleDateFormat sfSimpleYearMonth = new SimpleDateFormat("yyyyMMdd");

    public OSSManager(String accessKeyId, String secretKeyId, String securityToken) {
        endpoint = SZUtil.getAppMetaDataString(SZManager.getInstance().getContext(), SZConst.ENDPOINT);
        bucket = SZUtil.getAppMetaDataString(SZManager.getInstance().getContext(), SZConst.BUCKET);
        if (TextUtils.isEmpty(endpoint) || TextUtils.isEmpty(bucket)) {
            throw new IllegalArgumentException("endpoint or bucket not init...");
        }
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, secretKeyId, securityToken);
        oss = new OSSClient(SZManager.getInstance().getContext(), endpoint, credentialProvider);
    }

//    private void init(){
//
//        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
//        ClientConfiguration conf = new ClientConfiguration();
//        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
//        conf.setSocketTimeout(60 * 1000); // socket超时，默认15秒
//        conf.setMaxConcurrentRequest(9); // 最大并发请求数，默认5个
//        conf.setMaxErrorRetry(1); // 失败后最大重试次数，默认2次
//        oss = new OSSClient(SZApp.getInstance().getApplicationContext(), endpoint, credentialProvider, conf);
//    }
//    private OSSManager() {
//    }

//    public static OSSManager getInstance() {
//        if (INSTANCE == null) {
//            synchronized (OSSManager.class) {
//                if (INSTANCE == null) {
//                    INSTANCE = new OSSManager();
//                }
//            }
//        }
//        return INSTANCE;
//    }

    public OSSAsyncTask uploadWithMD5Verify(final String uploadFilePath, final OSSUploadProgressListener listener) {
        String uid = UUID.randomUUID().toString().replace("-", "");
        String date = sfSimpleYearMonth.format(new Date());
        final String objName = date + "/" + uid + ".png";
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(bucket, objName, uploadFilePath);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                if (listener != null) {
                    listener.onUpload(uploadFilePath, request, currentSize, totalSize);
                }
            }
        });
        return oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                SZUtil.log("=========================UploadSuccess========================");
                if (listener != null) {
                    listener.onSuccess(uploadFilePath, objName, request, result);
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                if (SZApp.getInstance().getTopActivity() != null) {
                    SZApp.getInstance().getTopActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SZToast.error(SZApp.getInstance().getString(R.string.error_net_work));
                        }
                    });
                }
                SZUtil.log("=========================UploadFailure========================");
                if (listener != null) {
                    listener.onFailure(uploadFilePath);
                }
                // 请求异常
                if (clientException != null) {
                    // 本地异常如网络异常等
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    serviceException.printStackTrace();
                    // 服务异常
//                    SZUtil.log("ErrorCode:"+serviceException.getErrorCode());
//                    SZUtil.log("RequestId:"+serviceException.getRequestId());
//                    SZUtil.log("HostId:"+serviceException.getHostId());
//                    SZUtil.log("RawMessage:"+serviceException.getRawMessage());
                }
            }
        });
    }

    public interface OSSUploadProgressListener {
        void onUpload(String uploadFilePath, PutObjectRequest request, long currentSize, long totalSize);

        void onSuccess(String uploadFilePath, String objName, PutObjectRequest request, PutObjectResult result);

        void onFailure(String uploadFilePath);
    }
}
